package com.hyts.standardcloud.security.sso.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

@EnableAuthorizationServer
@Configuration
public class JWTServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;

    // jwt的生成器
    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        jwtAccessTokenConverter.setSigningKey("abcxyz");
        return jwtAccessTokenConverter;
    }
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.accessTokenConverter(jwtAccessTokenConverter())  //配置JWT的生成器
                 .allowedTokenEndpointRequestMethods(HttpMethod.POST, HttpMethod.GET);
    }
    // 客户端的配置
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()  //
                .withClient("standard-cloud-facade") // client_id
                .secret("$2a$10$hD18k9cC6pMgOx9JyRH8EO7yBzQXPYCFi6hBxvBEId9KE.o8MAPB2") // client_secret
                .authorizedGrantTypes("authorization_code")  //采用什么方式获取access_token
                .redirectUris("http://localhost:8090/login")
                .scopes("all")
                .autoApprove(true);//自动授权
//                .and()
//                .withClient("client-b") // client_id
//                .secret("$2a$10$GqJuJhe7zmtwwThIed7smu9zMJBgSQzFMP47eEDL.g9tg8Y82.A7m") // client_secret
//                .authorizedGrantTypes("authorization_code")  //采用什么方式获取access_token
//                .redirectUris("http://localhost:8082/clientB/login")
//                .scopes("all")
//                .autoApprove(true);
    }
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.allowFormAuthenticationForClients()
                .checkTokenAccess("isAuthenticated()")
                .passwordEncoder(passwordEncoder);
    }
}
